import peewee_async
from base import BaseHandler # 用户模块
from db import Usermodel,Productmodel,Ordermodel  # 导入用户模型类
from tornado.web import url  # 导入torando路由
from utils import create_code,EmailTool,MyJwt,MyFile,jwt_token,WriteFile,Upyun,Page,acl_auth,rbac_auth
from werkzeug.security import check_password_hash,generate_password_hash
from PIL import ImageDraw,Image,ImageFont # 绘制图片   图片  字体
import re # 正则
import hashlib # 加密
import io
import random
import time
import requests
from db import database
import json
import os
from functools import wraps
from abc import ABCMeta,abstractmethod
from playhouse.shortcuts import model_to_dict     # 序列化


class Login(BaseHandler):
    async def get(self):
        usercode = self.get_argument('username',None)
        password = self.get_argument('password',None)
        if not usercode and not password:
            return self.finish({'errcode': 2, 'msg': '信息不完整'})
        try:
            user = await self.application.objects.get(Usermodel.select().where((Usermodel.usercode==usercode)&(Usermodel.password==password)))
        except Exception as e:
            return self.finish({'errcode':1,'msg':'账号或密码错误'})
        return self.finish({'errcode': 0, 'msg': '登录成功','uid':user.id,'username':user.usercode})

class GoodsList(BaseHandler):
    async def get(self):
        goods = await self.application.objects.execute(Productmodel.select())
        goodlist = [model_to_dict(i) for i in goods]
        print(goodlist)
        return self.finish({'errcode': 0, 'msg': '获取商品成功', 'data':goodlist})


class Order(BaseHandler):
    async def post(self):
        name = self.get_argument('name',None)
        phone = self.get_argument('phone',None)
        if not name and not phone:
            return self.finish({'errcode': 2, 'msg': '信息不完整'})
        ph = re.match(r'1[3-9]\d{9}',phone)
        if not ph:
            return self.finish({'errcode': 3, 'msg': '手机号格式不对,请输入正确的手机号'})
        try:
            await self.application.objects.get(Usermodel.select().where((Usermodel.name==name)&(Usermodel.phone==phone)))
        except Exception as e:
            return self.finish({'errcode': 4, 'msg': '手机号与姓名与证件不一致'})
        uid = self.get_argument('uid',None)
        gid = self.get_argument('gid',None)
        price = self.get_argument('price',None)
        order_id = str(int(time.time()))+str(uid)
        try:
            await self.application.objects.create(Ordermodel,users_id=uid,goods_id=gid,price=price,order_id=order_id)
        except Exception as e:
            return self.finish({'errcode': 1, 'msg': '订单创建失败'})
        return self.finish({'errcode': 0, 'msg': '生成订单成功','order_id':order_id})

    async def get(self):
        uid = self.get_argument('uid', None)
        orders = await self.application.objects.execute(Ordermodel.select().where(Ordermodel.users_id==uid))
        if not orders:
            return self.finish({'errcode': 1, 'msg': '你还没有订单'})
        orderlist = [model_to_dict(i) for i in orders]
        print(orderlist)
        return self.finish({'errcode': 0, 'msg': '获取我的订单成功', 'data':orderlist })



urlpatterns = [
    url('/login/',Login),
    url('/goods/',GoodsList),
    url('/order/',Order),
]













